﻿#region [===== Using =====]
using System;
using System.Collections.Generic;
using System.Security.Permissions;
using System.Web;
using Microsoft.SharePoint;
using Microsoft.SharePoint.Security;
using Microsoft.SharePoint.Utilities;
using Microsoft.SharePoint.WebControls;
using Microsoft.SharePoint.Workflow;
#endregion

namespace TPG.SharePoint.Workflow
{
    /// <summary>
    /// Represents a button on a SharePoint toolbar used for linking to 
    /// the bulk task selection page.
    /// </summary>
    [SharePointPermission(SecurityAction.InheritanceDemand, ObjectModel = true)]
    [SharePointPermission(SecurityAction.LinkDemand, ObjectModel = true)]
    [AspNetHostingPermission(SecurityAction.InheritanceDemand, Level = AspNetHostingPermissionLevel.Minimal)]
    [AspNetHostingPermission(SecurityAction.LinkDemand, Level = AspNetHostingPermissionLevel.Minimal)]
    public class BulkTaskProcessingButton : MenuItemTemplate
    {
        #region [===== Protected methods =====]
        protected override void OnInit(EventArgs eventArgs)
        {
            SPList list = SPContext.Current.List;

            Dictionary<SPWorkflowAssociation, string[]> workflowAssociations = new Dictionary<SPWorkflowAssociation, string[]>();

            foreach (SPContentType contentType in list.ContentTypes)
                foreach (SPWorkflowAssociation wfassoc in contentType.WorkflowAssociations)
                    if (!workflowAssociations.ContainsKey(wfassoc) && (wfassoc.BaseTemplate["Task_BulkIds"] != null))
                        workflowAssociations.Add(wfassoc, null);
            foreach (SPWorkflowAssociation wfassoc in list.WorkflowAssociations)
                if (!workflowAssociations.ContainsKey(wfassoc) && (wfassoc.BaseTemplate["Task_BulkIds"] != null))
                    workflowAssociations.Add(wfassoc, null);

            this.Visible = (workflowAssociations.Count != 0);

            if (this.Visible)
            {
                this.MenuGroupId = 500;
                this.Text = "Process tasks in bulk.";
                this.Description = "";


                string serverRelativeUrl = SPContext.Current.Web.ServerRelativeUrl;
                if (!serverRelativeUrl.EndsWith("/", StringComparison.Ordinal))
                    serverRelativeUrl = serverRelativeUrl + "/";
                string str2 = serverRelativeUrl + "_layouts/WSS3Workflow/BulkTaskList.aspx?List=";

                string keyOrValueToEncode = SPContext.Current.ListId.ToString("B").ToUpperInvariant();
                base.ClientOnClickNavigateUrl = "javascript:GoToPage('" + SPHttpUtility.UrlPathEncode(str2, true) + SPHttpUtility.UrlKeyValueEncode(keyOrValueToEncode) + "');";
                base.ImageUrl = "/_layouts/images/CompleteAllWFTasks.gif";
            }
            base.OnInit(eventArgs);
        }
        #endregion
    }
}
